package com.qiguliuxing.dts.admin.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.CouponConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsCoupon;
import com.qiguliuxing.dts.db.domain.DtsCouponUser;
import com.qiguliuxing.dts.service.base.DtsCouponService;
import com.qiguliuxing.dts.service.base.DtsCouponUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/coupon")
@Validated
@Api(tags = ApiAdminConsts.Coupon.PARENT)
public class AdminCouponController {
	private static final Logger logger = LoggerFactory.getLogger(AdminCouponController.class);

	@Autowired
	private DtsCouponService couponService;
	@Autowired
	private DtsCouponUserService couponUserService;

	@RequiresPermissions("admin:coupon:list")
	@RequiresPermissionsDesc(menu = { "推广管理", "优惠券管理" }, button = "查询")
	@GetMapping("/list")
	@ApiOperation(value=ApiAdminConsts.Coupon.LIST)
	@WebLog(description = ApiAdminConsts.Coupon.LIST,excludes = {LogParamsConsts.RESPONSE})
	public Object list(
			@ApiParam(value = "名称") String name,
			@ApiParam(value = "类型") Short type,
			@ApiParam(value = "状态") Short status,
			@ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
			@ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
			@ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
			@ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		List<DtsCoupon> couponList = couponService.querySelective(name, type, status, page, limit, sort, order);
		long total = PageInfo.of(couponList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", couponList);
		return ResponseUtils.ok(data);
	}

	@RequiresPermissions("admin:coupon:listuser")
	@RequiresPermissionsDesc(menu = { "推广管理", "优惠券管理" }, button = "查询用户")
	@ApiOperation(value=ApiAdminConsts.Coupon.USER_LIST)
	@GetMapping("/listuser")
	@WebLog(description = ApiAdminConsts.Coupon.USER_LIST,excludes = {LogParamsConsts.RESPONSE})
	public Object listuser(@ApiParam(value = "用户id") Integer userId,
						   @ApiParam(value = "优惠券id") Integer couponId,
						   @ApiParam(value = "优惠券状态") Short status,
						   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
						   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
						   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
						   @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		List<DtsCouponUser> couponList = couponUserService.queryList(userId, couponId, status, page, limit, sort,
				order);
		long total = PageInfo.of(couponList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", couponList);
		return ResponseUtils.ok(data);
	}

	private Object validate(DtsCoupon coupon) {
		String name = coupon.getName();
		if (StringUtils.isEmpty(name)) {
			return ResponseUtils.badArgument();
		}
		return null;
	}

	@RequiresPermissions("admin:coupon:create")
	@RequiresPermissionsDesc(menu = { "推广管理", "优惠券管理" }, button = "添加")
	@ApiOperation(value=ApiAdminConsts.Coupon.CREATE)
	@PostMapping("/create")
	@WebLog(description = ApiAdminConsts.Coupon.CREATE,persistence = true)
	public Object create(@RequestBody DtsCoupon coupon) {
		Object error = validate(coupon);
		if (error != null) {
			return error;
		}

		// 如果是兑换码类型，则这里需要生存一个兑换码
		if (coupon.getType().equals(CouponConsts.TYPE_CODE)) {
			String code = couponService.generateCode();
			coupon.setCode(code);
		}

		couponService.add(coupon);
		return ResponseUtils.ok(coupon);
	}

	@RequiresPermissions("admin:coupon:read")
	@RequiresPermissionsDesc(menu = { "推广管理", "优惠券管理" }, button = "详情")
	@ApiOperation(value=ApiAdminConsts.Coupon.READ)
	@GetMapping("/read")
	@WebLog(description = ApiAdminConsts.Coupon.READ)
	public Object read(@ApiParam(value = "优惠券id") @NotNull Integer id) {
		DtsCoupon coupon = couponService.findById(id);
		return ResponseUtils.ok(coupon);
	}

	@RequiresPermissions("admin:coupon:update")
	@RequiresPermissionsDesc(menu = { "推广管理", "优惠券管理" }, button = "编辑")
	@ApiOperation(value=ApiAdminConsts.Coupon.UPDATE)
	@PostMapping("/update")
	@WebLog(description = ApiAdminConsts.Coupon.UPDATE,persistence = true)
	public Object update(@RequestBody DtsCoupon coupon) {
		Object error = validate(coupon);
		if (error != null) {
			return error;
		}
		if (couponService.updateById(coupon) == 0) {
			return ResponseUtils.updatedDataFailed();
		}
		return ResponseUtils.ok(coupon);
	}

	@RequiresPermissions("admin:coupon:delete")
	@RequiresPermissionsDesc(menu = { "推广管理", "优惠券管理" }, button = "删除")
	@ApiOperation(value=ApiAdminConsts.Coupon.DELETE)
	@PostMapping("/delete")
	@WebLog(description = ApiAdminConsts.Coupon.DELETE,persistence = true)
	public Object delete(@RequestBody DtsCoupon coupon) {
		couponService.deleteById(coupon.getId());
		return ResponseUtils.ok();
	}
}
